package com.singlemountaintech.haogongjiang.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.singlemountaintech.haogongjiang.R;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 这个类存放各个方法的类
 * Created by Administrator on 2016/9/28.
 */
public class CodeUtils {


    private SpannableString ss;


    /**
     * 判断手机号码是否合法
     */
    public static boolean judgePhoneNumber(String str) {
//        String regular_phone_number = "^[1]([3][0-9]{1}|45|47|50|51|52|53|55|56|57|58|59|70|71|76|77|78|80|81|82|83|84|85|86|87|88|89)[0-9]{8}$";
        String regular_phone_number = "^1[34578]\\d{9}$";

        //Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");
        Pattern p = Pattern.compile(regular_phone_number);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证注册密码是否正确
     * 6-16位数字密码组合
     */
    public static final boolean isRightPwd(String pwd) {
        Pattern p = Pattern.compile("^(?![^a-zA-Z]+$)(?!\\D+$)[0-9a-zA-Z]{6,16}$");
        Matcher m = p.matcher(pwd);
        return m.matches();

    }

    /**
     * 验证推荐是否正确
     * 10位数字密码组合
     */
    public static final boolean isRightTuiJianMa(String pwd) {
        Pattern p = Pattern.compile("^(?![^a-zA-Z]+$)(?!\\D+$)[0-9a-zA-Z]{10,10}$");
        Matcher m = p.matcher(pwd);
        return m.matches();

    }

    /**
     * 验证注册密码是否正确
     * 6-16位数字密码（不要求组合）
     */
    public static final boolean isRightPwdGroup(String pwd) {
        Pattern p = Pattern.compile("^[0-9a-zA-Z]{6,16}$");
        Matcher m = p.matcher(pwd);
        return m.matches();

    }

    /**
     * 验证姓名是否合法(英文，数字，中文)
     *
     * @param name
     * @return
     */
    public static final boolean isRightName(String name) {//   [\u4E00-\u9FA5]+
        Pattern p = Pattern.compile("^[0-9a-zA-Z\u4E00-\u9FA5]");
        Matcher m = p.matcher(name);
        return m.matches();
    }

    /**
     * 验证登录密码是否正确
     */
    public static final boolean isRightLoginPwd(String pwd) {
        Pattern p = Pattern.compile("^\\w{8}(,\\w{8})*$");
        Matcher m = p.matcher(pwd);
        return m.matches();

    }

    /**
     * 身份证是否正确
     */
    public static final boolean isRightIdcard(String pwd) {
        String regular_Idcard = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        Pattern p = Pattern.compile(regular_Idcard);
        Matcher m = p.matcher(pwd);
        return m.matches();

    }

    /**
     * 输入内容只包含汉字
     */
    public static final boolean isHanZi(String pwd) {

        boolean b = true;
        for (int i = 0; i < pwd.length(); i++) {
            if (!(pwd.charAt(i) + "").matches("[\\u4E00-\\u9FA5]+")) {
                b = false;
                continue;
            }
        }
        return b;
    }

    /**
     * 包含4位不同数字
     *
     * @param str
     */
    public static boolean isRightPayPwd4(String str) {
        Set<Character> pwdList = new HashSet<>();
        for (int i = 0; i < str.length(); i++) {
            pwdList.add(str.charAt(i));
        }
        return pwdList.size() < 4 ? false : true;
    }

    /**
     * 连续数字<=3
     *
     * @param str
     */
    public static boolean isRightPayPwd3(String str) {
        boolean b = true;
        for (int i = 0; i < str.length() - 2; i++) {
            int i1 = Integer.parseInt(str.charAt(i) + "");
            int i2 = Integer.parseInt(str.charAt(i + 1) + "");
            int i3 = Integer.parseInt(str.charAt(i + 2) + "");
            if (((i1 + 1) == i2 && (i2 + 1) == i3) || ((i3 + 1) == i2 && (i2 + 1) == i1)) {
                b = false;
                break;
            }
        }
        return b;
    }

    /**
     * 更改获取验证码的TextView显示的内容
     */
    public static void setSecurityTextView(final TextView textView) {
        CountDownTimer countDownTimer = new CountDownTimer(90 * 1000, 1000) {
            public void onTick(long millisUntilFinished) {
                // mTextField.setText("seconds remaining: " + TimeUtils.formatDuration((int)millisUntilFinished));
                textView.setText(millisUntilFinished / 1000 + "秒");
                textView.setTextColor(Color.parseColor("#FFc300"));
                textView.setBackgroundDrawable(UiUtils.getDrawable(R.drawable.btn_bg_line_yellow));
                textView.setEnabled(false);
            }

            public void onFinish() {
                textView.setText("重新获取");
                textView.setTextColor(Color.parseColor("#FFc300"));
                textView.setBackgroundDrawable(UiUtils.getDrawable(R.drawable.btn_bg_line_yellow));
                textView.setEnabled(true);
                if (mCodeListener != null) {
                    mCodeListener.onFinish();
                }

            }
        };
        countDownTimer.start();
    }


    public static String getIP(Context context){

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address))
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex){
            ex.printStackTrace();
        }
        return null;
    }



    public interface CodeListener {
        void onFinish();
    }

    private static CodeListener mCodeListener;

    public static void setmCodeListener(CodeListener codeListener) {
        mCodeListener = codeListener;
    }

    /**
     * 设置下划线
     * 利用可变参数
     */
    public static void setUnderline(TextView... tv) {
        for (int i = 0; i < tv.length; i++) {
            tv[i].getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
            tv[i].getPaint().setAntiAlias(true);//抗锯齿
        }
    }

    /**
     * 获取版本信息
     */
    public static String getAppInfo(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = context.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return pkName + "#" + versionName + "#" + versionCode;
        } catch (Exception e) {
        }
        return null;
    }

    public static String getDeviceId(Context context) {
        String deviceId = "";

        if (deviceId == null || "".equals(deviceId)) {
            try {
                deviceId = getLocalMac(context).replace(":", "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (deviceId == null || "".equals(deviceId)) {
            try {
                deviceId = getAndroidId(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (deviceId == null || "".equals(deviceId)) {

            if (deviceId == null || "".equals(deviceId)) {
                UUID uuid = UUID.randomUUID();
                deviceId = uuid.toString().replace("-", "");
            }
        }
        return deviceId;
    }

    // IMEI码
    private static String getIMIEStatus(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    // Mac地址
    private static String getLocalMac(Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    // Android Id
    private static String getAndroidId(Context context) {
        String androidId = Settings.Secure.getString(
                context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    /**
     * 把光标移动到指定输入框
     */
    public static void setEditTextSelection(EditText et) {
        // 把焦点移动到验证码的输入框
        et.requestFocus();
        // 设置光标
        et.setSelection(0);
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public static String Md5(String str) {
        if (str != null && !str.equals("")) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
                byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < md5Byte.length; i++) {
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);
                }
                str = sb.toString();
            } catch (NoSuchAlgorithmException e) {
            } catch (Exception e) {
            }
        }
        return str;
    }

    public static byte[] hmacSha1(String key, String data) {
        try {
            SecretKeySpec sks = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(sks);
            return mac.doFinal(data.getBytes());
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            throw new RuntimeException("hacSha1 error", e);
        }
    }

    public static String ToJson(Map map) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);
        return jsonStr;
    }

    /**
     * Activity的启动动画，从下弹出
     *
     * @param activity
     */
    public static void starActivityDown(Activity activity) {
        activity.overridePendingTransition(R.anim.activity_open_up_in, R.anim.activity_open_blackscreen_exit);
    }

    /**
     * Activity的关闭动画，从下面滑出
     *
     * @param activity
     */
    public static void finishActivityDown(Activity activity) {
        activity.overridePendingTransition(R.anim.activity_open_blackscreen_exit, R.anim.activity_close_down_out);
    }
}
